import React, {useEffect, useState} from 'react'
import {Button} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect} from 'umi'
import {ArrowDownOutlined} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import {getDict} from '@/service/common/dict'
import {modelSeriesFun, translateDataToTree} from '@/utils/common'
import {getAllCitys, getCompany} from '@/service/common'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {
	getAllChannelType,
	getAllDitch,
	getRewardsList,
} from '@/service/merchantCenter/rewardDetails'
import {downloadDocumentUrl} from '@/service/common/download'
import {getFirstChannelType} from '@/service/channel'
import {getCarTypeList} from '@/service/carMessage/list'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {formatDate} from '@/utils/common/dateFilter'
import {carCategory, energyType} from '../../dict'

interface DataType {
	showArchivesAuditButton: any
	showEditButton: any
	archivesInstanceId: string
	id: string | string[] | null
	supplierCode: string
	supplierName: string
	orgId: string
	serviceType: string
	number: string
	contacts: string
	status: number
	date: string
}

const formItemLayout = {
	labelCol: {flex: '140px'},
	wrapperCol: {flex: '1'},
}

const rewardDetails = (props: {
	user: {orgId: string | number; userId: string | number}
}) => {
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [companyData, setCompanyData] = useState([]) // 公司数据
	const [channelList, setChannelList] = useState() // 渠道列表
	const [subjectList, setSubjectList] = useState([]) // 获取主体数据
	const [citysList, setCitysList] = useState([]) // 城市数据
	const [carTypeList, setCarTypeList] = useState<any>([]) // 品牌车系车型
	const [firstChannelData, setFirstChannelData] = useState([]) // 一级渠道类型
	const [secondChannelData, setSecondChannelData] = useState<any[]>([]) // 二级渠道类型
	const [loading, setLoading] = useState<boolean>(false)
	const [dictData, setDictData] = useState<any>({})
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	/** 获取主题数据 */
	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}
	/** 获取渠道列表 */
	const getDitchListFun = () => {
		getAllDitch().then((res: any) => {
			if (res?.success) {
				setChannelList(res.data)
			}
		})
	}
	/** 获取品牌车系 */
	const onCarTypeListFun = () => {
		getCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}
	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res?.data)
			}
		})
	}
	/** 获取一级渠道类型 */
	const getFirstChannelTypeFun = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.success) {
				setFirstChannelData(() => res?.data)
			}
		})
	}
	/** 获取二级渠道类型 */
	const getAllChannelTypeFun = () => {
		getAllChannelType().then((res: any) => {
			if (res?.success) {
				const arr: any[] = []
				res?.data?.forEach((item: any) => {
					item?.secondChannelType.forEach((items: any) => {
						arr.push(items)
					})
				})
				setSecondChannelData(arr)
			}
		})
	}

	// 获取公司列表
	const onCompany = () => {
		getCompany({merchantId: props.user.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props.user.orgId])
	useEffect(() => {
		getSubjectFun()
		getDitchListFun()
		getCitysFun()
		onCarTypeListFun()
		getAllChannelTypeFun()
		getFirstChannelTypeFun()
		getDict(
			{
				dictKeys: ['order_rent_type', 'star_rating'],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	// 获取渠道奖励明细列表
	const getData = () => {
		setLoading(true)
		getRewardsList({
			...params,
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch(() => {
				setDataSourse([])
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	const columns: ColumnsType<DataType> = [
		{
			title: '费用发生月份',
			dataIndex: 'expenseMouth',
			align: 'center',
			width: 120,
		},
		{
			title: '费用发生日期',
			dataIndex: 'expenseDate',
			align: 'center',
			width: 160,
			render: (text) => moment(text).format('YYYY-MM-DD'),
		},
		{
			title: '主体id',
			dataIndex: 'subjectId',
			align: 'center',
			width: 160,
		},
		{
			title: '主体',
			dataIndex: 'subjectName',
			align: 'center',
			width: 120,
		},
		{
			title: '公司id',
			dataIndex: 'orgId',
			align: 'center',
			width: 120,
		},
		{
			title: '公司名称',
			dataIndex: 'orgName',
			align: 'center',
			width: 180,
		},
		{
			title: '城市id',
			dataIndex: 'cityId',
			align: 'center',
			width: 120,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 120,
		},
		{
			title: 'AMC一级渠道类型',
			dataIndex: 'firstLevelTypeStr',
			align: 'center',
			width: 150,
		},
		{
			title: 'AMC二级渠道类型',
			dataIndex: 'secondLevelTypeStr',
			align: 'center',
			width: 150,
		},
		{
			title: '渠道id',
			dataIndex: 'ditchId',
			align: 'center',
			width: 120,
		},
		{
			title: '渠道code码',
			dataIndex: 'code',
			align: 'center',
			width: 120,
		},
		{
			title: '渠道名称',
			dataIndex: 'ditchName',
			align: 'center',
			width: 120,
		},
		{
			title: '对应阶梯',
			dataIndex: 'stair',
			align: 'center',
			width: 120,
		},
		{
			title: '单期拉新费（元）',
			dataIndex: 'pullFee',
			align: 'center',
			width: 150,
		},
		{
			title: '订单拉新总费用（元）',
			dataIndex: 'pullFeeTotal',
			align: 'center',
			width: 180,
		},
		{
			title: '跟单BD渠道id',
			dataIndex: 'bdId',
			align: 'center',
			width: 120,
			render: (text) =>
				text === -99 || text === 0 || text === -1 ? '--' : text,
		},
		{
			title: 'BD跟单费',
			dataIndex: 'bdCost',
			align: 'center',
			width: 120,
		},
		{
			title: '税率',
			dataIndex: 'taxRate',
			align: 'center',
			width: 120,
		},
		{
			title: '订单拉新不含税总费用',
			dataIndex: 'noIncludedFee',
			align: 'center',
			width: 120,
		},
		{
			title: '订单号',
			dataIndex: 'carOrderId',
			align: 'center',
			width: 120,
		},
		{
			title: '是否有效拉新',
			dataIndex: 'isEffective',
			align: 'center',
			width: 120,
			render: (text) => (text === 1 ? '是' : '否'),
		},
		{
			title: '司机是否有人证',
			dataIndex: 'isWitness',
			align: 'center',
			width: 140,
			render: (text) => (text === 1 ? '是' : '否'),
		},
		{
			title: '月租金',
			dataIndex: 'rentAmount',
			align: 'center',
			width: 120,
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			align: 'center',
			width: 120,
		},
		{
			title: '订单总租金',
			dataIndex: 'rentTotal',
			align: 'center',
			width: 120,
		},
		{
			title: '租赁类型',
			dataIndex: 'leaseTypename',
			align: 'center',
			width: 120,
		},
		{
			title: '车架号',
			dataIndex: 'vinNo',
			align: 'center',
			width: 120,
		},
		{
			title: '车辆品类',
			dataIndex: 'carCategory',
			align: 'center',
			width: 120,
			render: (text) => (
				<>
					{carCategory?.map((item) => {
						if (item?.key === text) {
							return item?.label
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '能源类型',
			dataIndex: 'energyType',
			align: 'center',
			width: 120,
			render: (text) => (
				<>
					{energyType?.map((item) => {
						if (item?.key === text) {
							return item?.label
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '车型',
			dataIndex: 'modelName',
			align: 'center',
			width: 120,
		},
		{
			title: '车龄',
			dataIndex: 'vehicleAge',
			align: 'center',
			width: 120,
		},
		{
			title: '星级',
			dataIndex: 'starRating',
			align: 'center',
			width: 120,
			render: (text) => (
				<>
					{dictData?.star_rating?.map(
						(item: {dictKey: any; dictValue: any}) => {
							if (item?.dictKey === text) {
								return item?.dictValue
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '下单时间',
			dataIndex: 'createOrderTime',
			align: 'center',
			width: 120,
			render: (text) => moment(text).format('YYYY-MM-DD'),
		},
		{
			title: '订单提车时间',
			dataIndex: 'takeCarTime',
			align: 'center',
			width: 120,
			render: (text) => moment(text).format('YYYY-MM-DD'),
		},
		{
			title: '结算状态',
			dataIndex: 'settlementStatus',
			align: 'center',
			width: 120,
			render: (text) => (text === 1 ? '未结算' : '已结算'),
		},
		{
			title: '结算时间',
			dataIndex: 'settlementTime',
			align: 'center',
			width: 120,
			render: (text) => moment(text).format('YYYY-MM-DD'),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'select',
					label: '渠道',
					name: 'ditchId',
					key: 'ditchId',
					keys: 'id',
					title: 'ditchName',
					items: channelList,
				},
				{
					type: 'select',
					label: 'AMC一级渠道类型',
					name: 'firstLevelType',
					key: 'firstLevelType',
					keys: 'type',
					title: 'valueName',
					items: firstChannelData,
				},
				{
					type: 'select',
					label: 'AMC二级渠道类型',
					name: 'secondLevelType',
					key: 'secondLevelType',
					keys: 'value',
					title: 'valueName',
					items: secondChannelData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'dateRange',
					key: 'costTime',
					name: 'costTime',
					label: '费用发生日期',
				},
				{
					type: 'dateRange',
					key: 'settTime',
					name: 'settTime',
					label: '结算时间',
				},
				{
					type: 'select',
					key: 'settlementStatus',
					name: 'settlementStatus',
					label: '结算状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 1,
							text: '未结算',
						},
						{
							value: 2,
							text: '已结算',
						},
					],
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					key: 'subjectId',
					name: 'subjectId',
					label: '主体',
					keys: 'id',
					title: 'merchantName',
					items: subjectList,
				},
				{
					type: 'treeSelect',
					key: 'orgId',
					name: 'orgId',
					label: '公司',
					keys: 'id',
					title: 'name',
					treeData: companyData,
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
					items: [...citysList],
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'input',
					key: 'carOrderId',
					name: 'carOrderId',
					label: '订单号',
				},
				{
					type: 'select',
					key: 'isEffective',
					name: 'isEffective',
					label: '是否有效拉新',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 1,
							text: '是',
						},
						{
							value: 2,
							text: '否',
						},
					],
				},
				{
					type: 'dateRange',
					key: 'takeTime',
					name: 'takeTime',
					label: '提车时间',
				},
			],
		},
		{
			type: 'group',
			key: 'group5',
			groupItems: [
				{
					type: 'select',
					key: 'leaseType',
					name: 'leaseType',
					label: '租赁类型',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.order_rent_type,
				},
				{
					type: 'select',
					key: 'isWitness',
					name: 'isWitness',
					label: '司机是否有人证',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 1,
							text: '是',
						},
						{
							value: 2,
							text: '否',
						},
					],
				},
				{
					type: 'select',
					label: '品牌车型车系',
					name: 'modelId',
					key: 'modelName',
					keys: 'id',
					title: 'fullName',
					items: carTypeList,
				},
			],
		},
	]
	const onFinish = (values: any) => {
		const {costTime, settTime, takeTime, cityId, ...info} = values
		const costStartTime = formatDate(costTime?.[0], 'YYYY-MM-DD')
		const costEndTime = formatDate(costTime?.[1], 'YYYY-MM-DD')
		const settStartTime = formatDate(settTime?.[0], 'YYYY-MM-DD')
		const settEndTime = formatDate(settTime?.[1], 'YYYY-MM-DD')
		const takeStartTime = formatDate(takeTime?.[0], 'YYYY-MM-DD')
		const takeEndTime = formatDate(takeTime?.[1], 'YYYY-MM-DD')
		let modelNames = ''

		carTypeList.forEach((ele:any) => {
			if(ele.id === info.modelId){
				modelNames = ele.fullName
			}
		});
		delete info.modelId
		setSearchData({
			...info,
			modelName:modelNames,
			cityId: cityId?.[1],
			costStartTime,
			costEndTime,
			settStartTime,
			settEndTime,
			takeStartTime,
			takeEndTime,
		})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	return (
		<div className={styles.rewardDetails}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Permissions permissionID="amc_merchantCenter_rewardDetails_export">
						<Button
							icon={<ArrowDownOutlined />}
							className={styles.import}
							ghost
							size="small"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '175',
									queryDesc:
										'渠道奖励明细导出,resourceId:175',
									queryParam: searchData,
								})
							}}>
							导出
						</Button>
					</Permissions>
				</div>

				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(rewardDetails)
